package com.example.freshmanapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.freshmanapp.adapter.NewsAdapter;
import com.example.freshmanapp.polo.News;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    ListView lv_news;
    List<News> NewsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        newwork();



    }

    private void newwork() {

        String url="http://10.2.64.50:8080/app5/news/list";
        RequestQueue requestQueue= Volley.newRequestQueue(MainActivity.this);
        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, url, (String) null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    JSONArray list=jsonObject.getJSONArray("list");
                    Gson gson=new Gson();
                    List<News> NewsList=gson.fromJson(list.toString(),new TypeToken<List<News>>(){

                    }.getType());
                    NewsAdapter adapter = new NewsAdapter(MainActivity.this,NewsList);
                    lv_news.setAdapter(adapter);

                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("响应失败");

            }
        });
        requestQueue.add(jsonObjectRequest);



    }

    private void init() {
        lv_news=(ListView)findViewById(R.id.lv_news);


    }
}